registerJQueryFunction(function(selector,target){
        /**
         * Apply FB's functions to the newly created elements.
         */
        target.each(function(){
                FB.XFBML.parse(this);
        });

        /**
         * The "show comments" link.
         */
        selector('[ui_role=show_comments]').click(function(){
                var commentsSection=$(this).closest('[ui_role=comments_section]');
                commentsSection.htmlJQ(
                    renderEjs('facebook/comments',{href:commentsSection.attr('targetHref')})
                );
                return false;
        });

        /**
         * The "hide comments" link.
         */
        selector('[ui_role=hide_comments]').click(function(){
                var commentsSection=$(this).closest('[ui_role=comments_section]');
                commentsSection.htmlJQ(
                    renderEjs('facebook/comment_count',{href:commentsSection.attr('targetHref')})
                );
                return false;
        });

        /**
         * The "share" button.
         */
        selector('[ui_role=share_button]').click(function(){
                window.open(
                    'https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent($(this).attr('targetHref')),
                    'facebook-share-dialog',
                    'width=626,height=436');
        });
});

/**
 * Render a link to a Facebook user.
 *
 * `facebookUser` needs to be an object with `id` and `name` fields, or with an
 * `facebook_user` field that contains `id` and `name` fields.
 */
function facebookUser(facebookUser){
    if(facebookUser.facebook_user){
        facebookUser=facebookUser.facebook_user;
    }
    return renderEjs('facebook/user_name',{
            facebookUserId:facebookUser.id,
            facebookUsername:facebookUser.name,
            locationName:facebookUser.location_name
    });
}

/**
 * Load the Facebook JavaScript SDK.
 */
function loadFacebookSDK(appId){
    $.ajax({
            type:'GET',
            url:'//connect.facebook.net/en_UK/all.js',
            dataType:'script',
            success:function(){
                FB.init({
                        appId:appId
                });
                FB.Event.subscribe('comment.create',function(response){
                        ajaxRequest('facebook','notifyOnAction',response,function(data){
                        });
                });
                if(window.runAfterFacebookInit){
                    runAfterFacebookInit();
                    delete window.runAfterFacebookInit;
                }
                FB.Canvas.setAutoGrow();
                fixCanvasHeight();
            }
    });
}

/**
 * Generate a URL with Facebook reference for the supplied model object.
 */
function fbHrefFor(model){
    return facebookAppUrl+'?fb_ref='+encodeURIComponent(model.type+'#'+model.owner.id);
}
